﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using Controller.Class;
using Microsoft.Reporting.WebForms;
using Controller.Helper;
using Model;


namespace SalePriceSystem.Page
{
    public partial class ReportViewer : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                parameter.Visible = false;
                ReportDocumentActive();
                if (HttpContext.Current.Request.QueryString["cusID"] != null && HttpContext.Current.Request.QueryString["docs"] != null)
                {
                    string custID = Server.UrlDecode(HttpContext.Current.Request.QueryString["cusID"]);
                    string docsID = HttpContext.Current.Request.QueryString["docs"];

                    PrepareDataToCustomerReport(docsID, custID.Trim());
                }
                if (System.Web.HttpContext.Current.Request.QueryString["doctype"] != null)
                {
                    String docid = "";
                    string doctype = "";
                    doctype = System.Web.HttpContext.Current.Request.QueryString["doctype"].ToString();
                    docid = System.Web.HttpContext.Current.Request.QueryString["docid"].ToString();
                    if (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["sale"]))
                    {
                        RunDocDetaiReport(doctype, docid, false);
                    }
                    else
                    {
                        RunDocDetaiReport(doctype, docid, true);
                    }
                }
                string adminRole = WebConfigurationManager.AppSettings["AdminRoleName"] ?? "Admin";

                if (Controller.AD.LdapAuthentication.GetCurrentUserRole() != adminRole)
                {
                    DropDownList1.Items.Remove(new ListItem("Report Document", "Report2"));
                }
            }

        }
        
        private void PrepareDataToCustomerReport(string docsIDs, string custID)
        { 
            string[] docsID = docsIDs.Split(',');
            List<ProductDiscount> productDiscounts = Document.getProductDiscountByDocsID(docsID, custID);
            List<NDpriceReport> allNDPrice = Controller.Helper.NDPrice.GetlastestRoundNDPric(docsID[0]);
            string currentUser = Controller.AD.LdapAuthentication.GetCurrentUser();
            if (!string.IsNullOrEmpty(Controller.AD.LdapAuthentication.GetCurrentRepresendto()))
            {
                currentUser = Controller.AD.LdapAuthentication.GetCurrentRepresendto();
            }
            List<tblUser> u = Member.GetUserDB(currentUser);
            if (u.Count > 0)
            {
                allNDPrice[0].saleName = u[0].FirstName + " " + u[0].Lastname;
                allNDPrice[0].saleTel = u[0].Tel;
                allNDPrice[0].docsID = docsIDs;
            }
            if (custID.Length < 5)
            {
                allNDPrice[0].priceGrp = custID;
            }
            else
            {
                allNDPrice[0].customerName = Controller.Helper.Customer.GetCustomerbyID(custID).mcustname1;
            }

            List<tblUser> sc = Sale.GetSaleCoBySale(currentUser);
            string scName = string.Empty;
            string scTel = string.Empty;
            string scFax = string.Empty;
            if (sc.Count > 0)
            {
                string scname = null;
                string sctel = null;
                String scfax = null;
                var scTels = new List<string>();
                var scFaxs = new List<string>();
                foreach (var scItem in sc)
                {
                    scname += scItem.FirstName + " " + scItem.Lastname + Environment.NewLine;
                    var scTel2 = scItem.Tel ??  "";
                    var scFax2 = scItem.Fax ?? "";
                    foreach (var i in scTel2.Split(','))
                    {
                        if (!scTels.Contains(i))
                        {
                            scTels.Add(i);
                            sctel += i + Environment.NewLine;
                        }
                    }
                    foreach (var i in scFax2.Split(','))
                    {
                        if (!scFaxs.Contains(i))
                        {
                            scFaxs.Add(i);
                            scfax += i + Environment.NewLine;
                        }
                    }
                    
                }
                allNDPrice[0].saleCoName = scname;
                allNDPrice[0].saleCoTel = sctel;
                allNDPrice[0].saleCoFax = scfax;
            }

            //var newAllNDPrice = new List<NDpriceReport>();
            int countMatch = 0;
            foreach (var nDpriceReport in allNDPrice)
            {
                foreach (var pd in productDiscounts)
                {
                    if (pd.producGrpID == nDpriceReport.mprodh_grpID)
                    {
                        countMatch++;
                        if (pd.discountBath != -1)
                        {
                            nDpriceReport.discountPrice = pd.discountBath;
                        }
                        else
                        {
                            decimal dp = pd.discount;
                            nDpriceReport.discountPrice = nDpriceReport.discountPrice - dp;
                        }
                    }
                }
            }
            parameter.Visible = false;
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", allNDPrice));
            ReportViewer1.LocalReport.ReportPath = "Reports\\ReportLastestNdPrice.rdlc";
            ReportViewer1.LocalReport.Refresh();
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            runReport();

        }

        private void runReport()
        {

            string value = DropDownList1.SelectedValue;
            switch (value)
            {
                case "Report1":
                    parameter.Visible = false;
                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", Controller.Helper.NDPrice.GetlastestRoundNDPric()));
                    ReportViewer1.LocalReport.ReportPath = "Reports\\ReportLastestNdPrice.rdlc";
                    ReportViewer1.LocalReport.Refresh();
                    break;
                case "Report2":
                    parameter.Visible = true;
                    ReportViewer1.LocalReport.DataSources.Clear();
                    string doctype = DropDownList3.SelectedValue;
                    string status = DropDownListStatus.SelectedValue;
                    string datefrom = TextBox1.Text;
                    string dateTo = TextBox2.Text;
                    string[] username = {TextBoxSale.Text};


                    string salegroup = TextBoxSalegrp.Text.Trim();
                    if (!string.IsNullOrEmpty(salegroup))
                    {
                        username = Member.GetUserNameBySalegroup(salegroup);
                    }
                    DateTime DateForm;
                    DateTime DateTo;

                    if (!DateTime.TryParse(datefrom, out DateForm))
                    {
                        datefrom = "";
                    }
                    if (!DateTime.TryParse(dateTo, out DateTo))
                    {
                        dateTo = "";
                    }

                    ReportViewer1.LocalReport.EnableHyperlinks = true;
                    var ds = new List<ReportObjectDocument>();
                    foreach (var userName in username)
                    {
                        ds.AddRange(Document.getAllDocument(doctype, status, userName));
                    }
                    if (!string.IsNullOrEmpty(datefrom) && string.IsNullOrEmpty(dateTo))
                    {
                        DateForm = DateTime.Parse(datefrom);
                        DateForm = DateForm.AddYears(543);
                        var result = from data in ds
                                     where data.Created.ToUniversalTime() >= DateForm
                                     select data;
                        ds = result.ToList();
                    }
                    else if (string.IsNullOrEmpty(datefrom) && !string.IsNullOrEmpty(dateTo))
                    {
                        DateTo = DateTime.Parse(dateTo);
                        DateTo = DateTo.AddYears(543);
                        var result = from data in ds
                                     where data.Created.ToUniversalTime() <= DateTo.AddDays(1)
                                     select data;
                        ds = result.ToList();
                    }
                    else if (!string.IsNullOrEmpty(datefrom) && !string.IsNullOrEmpty(dateTo))
                    {
                        DateForm = DateTime.Parse(datefrom);
                        DateTo = DateTime.Parse(dateTo);
                        DateForm = DateForm.AddYears(543);
                        DateTo = DateTo.AddYears(543);
                        var result = from data in ds
                                     where data.Created.ToUniversalTime() >= DateForm && data.Created.ToUniversalTime() <= DateTo.AddDays(1)
                                     select data;
                        ds = result.ToList();
                    }

                    ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds));
                    ReportViewer1.LocalReport.ReportPath = "Reports\\ReportDocList.rdlc";
                    ReportViewer1.LocalReport.Refresh();

                    break;

            }
        }

        public void RunDocDetaiReport(string _doctype, string _docid, bool isSale)
        {
            ReportViewer1.LocalReport.DataSources.Clear();
            List<ReportObjectDocumentDetail> ds = Document.GetDocumentDetailByDocIDReport(_doctype, _docid);
            string username ="";
            if (ds.Count > 0)
            {
                int approveLevel = 0;
                foreach (var d in ds)
                {
                    var value = d.ddiscountprice - d.discountPrice;
                    if (value <= d.level1)
                    {
                        if (approveLevel < 1)
                        {
                            approveLevel = 0;
                        }
                    }
                    else if (value > d.level1 && value <= d.level2)
                    {
                        if (approveLevel < 1)
                        {
                            approveLevel = 1;
                        }
                    }
                    else if (value > d.level2 && value <= d.level3)
                    {
                        if (approveLevel < 2)
                        {
                            approveLevel = 2;
                        }
                    }
                    else if (value > d.level3)
                    {
                        if (approveLevel < 3)
                        {
                            approveLevel = 3;
                        }
                    }
                    d.RefID += "(" + Document.GetDocParent(d.docID, d.RefId2) + ")";

                    //if (isSale == true && d.discountPriceBath != null && d.discountPriceBath != -1)
                    //{
                    //    d.discountPrice = (decimal)d.discountPriceBath + d.ddiscountprice;
                    //}
                    
                }
                username = ds[0].usernameOwner;
                ds[0].approveLevel = approveLevel;
                List<tblUser> approvers = Controller.Helper.Member.GetUserDB(ds[0].approveByUserName);
               
                if (approvers.Count > 0)
                {
                    List<tblUser> us =  Controller.Helper.Member.GetUserDB(approvers[0].UserName);
                    if (us.Count > 0)
                    {
                        ds[0].imageLicense = us[0].ImageLicense;
                    }
                }
                var approvalAll = Approver.GetAllApproveLevelObject();
                string status = Document.GetStatus(_docid);
                if (!string.IsNullOrEmpty(status))
                {
                    ds[0].Status = status;
                }
                for (int i = 0; i < approvalAll.Count; i++)
                {
                    switch (i)
                    {
                        case 0:
                            ds[0].approverColor = approvalAll[0].warningColor;
                            ds[0].approverDisplay = approvalAll[0].approveDisplay;
                            break;
                        case 1 :
                            ds[0].approver1Color = approvalAll[1].warningColor;
                            ds[0].approver1Display = approvalAll[1].approveDisplay;
                            break;
                        case 2:
                            ds[0].approver2Color = approvalAll[2].warningColor;
                            ds[0].approver2Display = approvalAll[2].approveDisplay;
                            break;
                        case 3:
                            ds[0].approver3Color = approvalAll[3].warningColor;
                            ds[0].approver3Display = approvalAll[3].approveDisplay;
                            break;
                        case 4:
                            ds[0].approver4Color = approvalAll[4].warningColor;
                            ds[0].approver4Display = approvalAll[4].approveDisplay;
                            break;
                            
                    }
                }

            }
           
            ReportViewer1.LocalReport.EnableExternalImages = true;
            ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds));
            ReportViewer1.LocalReport.ReportPath = !isSale ? "Reports\\ReportDocDetail.rdlc" : "Reports\\ReportDocDetailSale.rdlc";
            ReportViewer1.LocalReport.Refresh();
            
        }
        
        private void ReportDocumentActive()
        {
            List<tblStatus> lS = DocumentStatus.GetAllStatus();
            tblStatus s = new tblStatus();
            s.StatusID = "99";
            lS.RemoveAt(lS.Count-1);

            DropDownListStatus.DataSource = lS;
            DropDownListStatus.DataTextField = "StatusDescription";
            DropDownListStatus.DataValueField = "StatusID";
            DropDownListStatus.DataBind();
            DropDownListStatus.Items.Insert(0, new ListItem("All", " "));

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            runReport();
        }
        
        protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
        {
            runReport();
        }

        protected void DropDownListStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            runReport();
        }


    }
}